package com.salon.modules.sys.controller;

import com.salon.common.http.response.ObjectResult;
import com.salon.common.http.response.ResultCode;
import com.salon.common.utils.Base64;
import com.salon.modules.sys.entity.SysMenuEntity;
import com.salon.modules.sys.entity.SysUserEntity;
import com.salon.modules.sys.entity.vo.RouterVo;
import com.salon.modules.sys.form.SysLoginForm;
import com.salon.modules.sys.service.ISysCaptchaService;
import com.salon.modules.sys.service.ISysMenuService;
import com.salon.modules.sys.service.ISysRoleService;
import com.salon.modules.sys.service.ISysUserService;
import com.salon.modules.sys.service.ISysUserTokenService;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import javax.annotation.Resource;
import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletResponse;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.crypto.hash.Sha256Hash;
import org.apache.shiro.subject.Subject;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

/**
 * 登录相关
 */
@RestController
@Api(tags="登录管理")
public class SysLoginController extends BaseController {

    @Resource
    private ISysUserService sysUserService;

    @Resource
    private ISysRoleService sysRoleService;

    @Resource
    private ISysMenuService sysMenuService;

    @Resource
    private ISysUserTokenService sysUserTokenService;

    @Resource
    private ISysCaptchaService sysCaptchaService;

    @GetMapping("/captcha.jpg")
    @ApiOperation("获取验证码")
    public ObjectResult<String> captcha(HttpServletResponse response, String uuid)
            throws IOException {
        response.setHeader("Cache-Control", "no-store, no-cache");
        response.setContentType("image/jpeg");
        //获取图片验证码
        BufferedImage image = sysCaptchaService.getCaptcha(uuid);
        ByteArrayOutputStream stream = new ByteArrayOutputStream();
        ImageIO.write(image, "jpg", stream);
        try {
            return ObjectResult.success(Base64.encode(stream.toByteArray()));
        } catch (Exception e) {
            e.printStackTrace();
            return ObjectResult.failed(ResultCode.SERVER_ERROR, e.getMessage());
        } finally {
            stream.close();
        }
    }

    @PostMapping("/sys/login")
    @ApiOperation("后台登录")
    public ObjectResult login(@RequestBody SysLoginForm form) {
        boolean captcha = sysCaptchaService.validate(form.getUuid(), form.getCaptcha());
        if (!captcha) {
            return ObjectResult.failed(ResultCode.FAIL, "验证码不正确");
        }
        // 用户信息
        SysUserEntity user = sysUserService.getUserInfoByName(form.getUsername());
        // 账号不存在、密码错误
        String hashPassword = new Sha256Hash(form.getPassword(), user.getSalt()).toHex();
        if (ObjectUtils.isEmpty(user) || !user.getPassword().equals(hashPassword)) {
            return ObjectResult.failed(ResultCode.FAIL, "账号或密码不正确");
        }
        // 账号锁定
        if (user.getStatus() == 0) {
            return ObjectResult.failed(ResultCode.FAIL, "账号已被锁定,请联系管理员");
        }
        // 生成token
        return sysUserTokenService.createToken(user.getUserId());
    }

    @GetMapping("/sys/info")
    @ApiOperation("登录信息")
    public ObjectResult<Map<String, Object>> info() {
        // 用户信息
        SysUserEntity user = getUser();
        // 角色集合
        Set<String> roles = sysRoleService.getRolePermission(user);
        // 权限集合
        Set<String> permissions = sysMenuService.getMenuPermission(user);
        // 菜单路由集合
        List<SysMenuEntity> menus = sysMenuService.listMenuTreeByUserId(user.getUserId());
        // 构建路由菜单
        List<RouterVo> routerList = sysMenuService.buildMenus(menus);
        // 返回用户信息体
        Map<String, Object> result = new HashMap<>();
        result.put("user", user);
        result.put("roles", roles);
        result.put("menus", routerList);
        result.put("permissions", permissions);
        return ObjectResult.success(result);
    }

    @PostMapping("/sys/logout")
    @ApiOperation("后台登出")
    public ObjectResult<String> logout() {
        Subject currentUser = SecurityUtils.getSubject();
        sysUserTokenService.logout(getUserId());
        currentUser.logout();
        return ObjectResult.success();
    }

}
